package a51qindian.com.comprehensive.activity;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;

import com.li.interfaces.OnItemClickListener;
import com.li.widget.DoubleTextView;
import com.li.widget.MultipleLayout;
import com.li.widget.TopNavigationBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import a51qindian.com.comprehensive.Const;
import a51qindian.com.comprehensive.R;
import a51qindian.com.comprehensive.base.QDBaseActivity;
import a51qindian.com.comprehensive.city.CityShopAdapter;
import a51qindian.com.comprehensive.items.LinearItemDecoration;
import a51qindian.com.comprehensive.model.AddressInfo;
import a51qindian.com.comprehensive.model.BaseModel;
import a51qindian.com.comprehensive.model.CountBaseModel;
import a51qindian.com.comprehensive.model.ShopInfo;
import a51qindian.com.comprehensive.net.ObservableHelper;
import a51qindian.com.comprehensive.net.RetrofitCreator;
import a51qindian.com.comprehensive.net.SelectorObserver;
import a51qindian.com.comprehensive.util.PopCondition;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;


/**
 * Author: Li
 * Date: 2017/10/24 0024
 * Description: 商铺列表
 */

public class ShopListActivity extends QDBaseActivity {

    @BindView(R.id.top_navigation)
    TopNavigationBar mTopNavigation;
    @BindView(R.id.recycler_shop)
    RecyclerView mRecyclerShop;
    @BindView(R.id.layout_refresh)
    SmartRefreshLayout mLayoutRefresh;
    @BindView(R.id.layout_content)
    MultipleLayout mLayoutContent;
    @BindView(R.id.pop_condition)
    PopCondition mPopCondition;
    @BindView(R.id.pop_condition_town)
    PopCondition mPopTown;
    @BindView(R.id.dtv_num)
    DoubleTextView mDtvNum;
    private List<ShopInfo> mShopInfoList;
    private CityShopAdapter mCityShopAdapter;
    private String mAreaId = "";
    private String mTownId = "";

    @Override
    protected int getLayoutId() {
        return R.layout.activity_shop_list;
    }

    @Override
    protected void initSth() {
        super.initSth();
        mTopNavigation.setNavigationBarListener(this);
        mShopInfoList = new ArrayList<>();
        setSmartRefreshLayout(mLayoutRefresh);
        mRecyclerShop.setLayoutManager(new LinearLayoutManager(this));
        mCityShopAdapter = new CityShopAdapter(mContext);
        mRecyclerShop.setAdapter(mCityShopAdapter);
        mRecyclerShop.addItemDecoration(new LinearItemDecoration());
        mCityShopAdapter.setItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int pos) {
                Intent intent = new Intent(ShopListActivity.this, DeviceListActivity.class);
                intent.putExtra("shopId", mShopInfoList.get(pos).getShop_id());
                startActivity(intent);
            }
        });
        mPopCondition.setOnBack(new PopCondition.OnBack() {
            @Override
            public void onBack() {
                mIsRefresh=true;
                mShopInfoList.clear();
                mCityShopAdapter.setShopInfoList(mShopInfoList);
                mDtvNum.setTxtRight("0");
                mAreaId = mPopCondition.getUId();
                mTownId = "";
                getTownList(mAreaId);
                showShopList(mUid, "0", mAreaId, mTownId);
            }
        });
        mPopTown.setOnBack(new PopCondition.OnBack() {
            @Override
            public void onBack() {
                mIsRefresh=true;
                mShopInfoList.clear();
                mCityShopAdapter.setShopInfoList(mShopInfoList);
                mDtvNum.setTxtRight("0");
                mAreaId = mPopCondition.getUId();
                mTownId = mPopTown.getUId();
                showShopList(mUid, "0", mAreaId, mTownId);
            }
        });

        getAddressList(mUid);
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        super.onRefresh(refreshlayout);
        showShopList(mUid, Const.DEFAULT_PAGE, mAreaId, mTownId);
    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        super.onLoadmore(refreshlayout);
        showShopList(mUid, String.valueOf(mPage + 1), mAreaId, mTownId);
    }


    /**
     * 获取区县
     *
     * @param uid 用户编号
     */
    private void getAddressList(String uid) {
        mLayoutContent.onLoadingWithContent();
        Map<String, String> map = new HashMap<>();
        map.put("uid", uid);
        ObservableHelper.createObservable(RetrofitCreator.createService().getAddressList(map))
                .subscribe(new SelectorObserver<BaseModel<List<AddressInfo>>>() {
                    @Override
                    protected void onErrorCodeInfo(int code, String info) {
                        mLayoutContent.onSuccess();
                        showToast(info);
                    }

                    @Override
                    protected void onSuccess(BaseModel<List<AddressInfo>> listBaseModel) {
                        mLayoutContent.onSuccess();
                        AddressInfo info = new AddressInfo();
                        info.setName("全区");
                        info.setUid("");
                        listBaseModel.getData().add(0, info);
                        mPopCondition.setData(listBaseModel.getData());
                        mAreaId = mPopCondition.getUId();
                        mTownId = "";
                        showShopList(mUid, "0", mAreaId, mTownId);
                        getTownList(mAreaId);
                    }

                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        mLayoutContent.onSuccess();
                        showToast(e.getMessage());
                    }
                });
    }

    /**
     * 获取街道编号
     *
     * @param areaId 区县编号
     */
    private void getTownList(String areaId) {
        if (TextUtils.isEmpty(areaId)) {
            List<AddressInfo> infos=new ArrayList<>();
            AddressInfo info=new AddressInfo();
            info.setUid("");
            info.setName("全部街道");
            infos.add(info);
            mPopTown.setData(infos);
            return;
        }

        Map<String, String> map = new HashMap<>();
        map.put("uid", areaId);
        ObservableHelper.createObservable(RetrofitCreator.createService().getAddressList(map))
                .subscribe(new SelectorObserver<BaseModel<List<AddressInfo>>>() {
                    @Override
                    protected void onErrorCodeInfo(int code, String info) {
                    }

                    @Override
                    protected void onSuccess(BaseModel<List<AddressInfo>> listBaseModel) {
                        mLayoutContent.onSuccess();
                        AddressInfo info = new AddressInfo();
                        info.setName("全部街道");
                        info.setUid("");
                        listBaseModel.getData().add(0, info);
                        mPopTown.setData(listBaseModel.getData());
                        mAreaId = mPopCondition.getUId();
                        mTownId = mPopTown.getUId();
                        showShopList(mUid, "0", mAreaId, mTownId);

                    }

                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                    }
                });
    }

    private void showShopList(String uid, String page, String area_id, String town_id) {
        mLayoutContent.onLoadingWithContent();
        Map<String, String> map = new HashMap<>();
        map.put("uid", uid);
        map.put("page", page);
        map.put("area_id", area_id);
        map.put("town_id", town_id);
        ObservableHelper.createObservable(RetrofitCreator.createService().lookShop(map))
                .subscribe(new SelectorObserver<CountBaseModel<List<ShopInfo>>>() {
                    @Override
                    protected void onErrorCodeInfo(int code, String info) {
                        mLayoutContent.onSuccess();
                        stopRefreshLoad();
                        mLayoutRefresh.setLoadmoreFinished(true);
                        showToast(info);
                    }

                    @Override
                    protected void onSuccess(CountBaseModel<List<ShopInfo>> listBaseModel) {
                        mLayoutContent.onSuccess();
                        if (mIsRefresh) {
                            mPage = 0;
                            mShopInfoList.clear();
                            mLayoutRefresh.setLoadmoreFinished(false);
                        } else {
                            mPage++;
                        }
                        stopRefreshLoad();
                        List<ShopInfo> shopInfoList = listBaseModel.getData();
                        if (!mIsRefresh && shopInfoList.size() < Const.DEFAULT_PAGE_SIZE) {
                            mLayoutRefresh.setLoadmoreFinished(true);
                        }
                        mShopInfoList.addAll(shopInfoList);
                        mCityShopAdapter.setShopInfoList(mShopInfoList);
                        mDtvNum.setTxtRight(listBaseModel.getCount());
                    }

                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        mLayoutContent.onSuccess();
                        stopRefreshLoad();
                        showToast(e.getMessage());
                    }
                });
    }

    @OnClick({R.id.pop_condition, R.id.dtv_num,R.id.pop_condition_town})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.pop_condition:
                mPopTown.dismiss();
                mPopCondition.showPop(view);
                break;
            case R.id.pop_condition_town:
                mPopCondition.dismiss();
                mPopTown.showPop(view);
            case R.id.dtv_num:
                break;
        }
    }

    @Override
    public void onBackPressed() {
        if (mPopCondition.getPop() != null && mPopCondition.getPop().isShowing()) {
            mPopCondition.getPop().dismiss();
            return;
        }

        if (mPopTown.getPop() != null && mPopTown.getPop().isShowing()) {
            mPopTown.getPop().dismiss();
            return;
        }
        super.onBackPressed();

    }
}
